// app/service/user.js
const Service = require('egg').Service;

function toInt(str) {
  if (typeof str === 'number') return str;
  if (!str) return str;
  return parseInt(str, 10) || 0;
}

class UserService extends Service {
  async update(body, _this) {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const user = await ctx.model.User.findByPk(decode?.id);
    if (!user) {
      ctx.status = 404;
      _this.fail('库里没有该条数据');
      return;
    }
    await user.update(body);
    _this.success(user);
    return user;
  }

  async getcurrentuser() {
    const { ctx, app } = this;
    const token = ctx.request.header.authorization;
    const decode = await app.jwt.verify(token, app.config.jwt.secret);
    const result = await ctx.model.User.findByPk(toInt(decode.id));
    let orginfo = {};
    if (result?.org_id) {
      orginfo = await ctx.model.Org.findByPk(toInt(result?.org_id));
    }
    return { ...orginfo.dataValues, ...result.dataValues };
  }
}

module.exports = UserService;
